import React from 'react';
import { AutoComplete, Empty, Select } from 'antd';
import { ObjectBox } from '/common/componentsTpl/ObjectBox';
import { connect } from 'dva';
import { isObjectValEqual } from '/common/utils/utils';
import isEmpty from 'lodash/isEmpty';
import map from 'lodash/map';
import omit from 'lodash/omit';

const Option = AutoComplete.Option;

class AutoCompleteComp extends ObjectBox {

  constructor(props) {
    super(props);
    const { nameKey } = props;
    const value = props.value || {};
    this.changingVal = value[nameKey] || '';
  }

  shouldComponentUpdate(nextProps, nextState) {
    if (!isObjectValEqual(nextProps.value, this.props.value)) {
      const nextValue = nextProps.value || {},
        nextNameKey = nextProps.nameKey;
      const curValue = this.props.value || {},
        curNameKey = this.props.nameKey;

      if (nextValue[nextNameKey] !== curValue[curNameKey]) {
        this.changingVal = nextValue[nextNameKey] || '';
        // console.log('>>> shouldComponentUpdate this.changingVal', this.changingVal);
      }
    }
    return super.shouldComponentUpdate(nextProps, nextState);
  }

  fetchData(forceReq = false) {
    // console.log('>>> this.changingVal', this.changingVal);
    const { asyncReqFunc } = this.props;
    if (asyncReqFunc) {
      asyncReqFunc(this.changingVal, forceReq, this.pageNo);
    } else {
      super.fetchData(forceReq, this.pageNo);
    }
  }

  /**
   * 弹框确认选择之后
   * @param checkedList
   */
  handleOk(checkedList) {
    const checkedItem = checkedList[0] || {};
    this.changingVal = checkedItem[this.props.nameKey] || '';
    super.handleOk(checkedList);
  }

  handleInputChange(inputVal) {
    if ('undefined' === typeof inputVal || '' === inputVal) {
      this.changingVal = inputVal;
      this.handleChange('');
    }

    if (true === this.isSelectAct) {
      this.isSelectAct = false;
      return false;
    }
    this.changingVal = inputVal;
    this.setState({ changingVal: this.changingVal });
  }

  renderMain(opt = {}) {
    // console.log('>>> render this.changingVal', this.changingVal);
    const { primaryKey, nativeProps = {}, asyncSearch, global, appCode } = this.props;
    const compData = !isEmpty(this.props.compData) ? this.props.compData : global[appCode] || [];

    const enterProps = asyncSearch ? {
      onChange: (inputVal) => {
        if (false === this.handleInputChange(inputVal)) return false;

        window.clearTimeout(this.enterTimeoutIns);
        this.enterTimeoutIns = window.setTimeout(() => {
          this.pageNo = 1;
          this.fetchData(true);
          // asyncReqFunc(this.changingVal, true, 1);
        }, 500);
      },
    } : {
      onChange: this.handleInputChange.bind(this),
    };

    return (
      <AutoComplete
        {...enterProps}
        showArrow={false}
        allowClear
        notFoundContent={<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={'无匹配数据'}/>}
        optionLabelProp="text"
        value={this.changingVal}
        // defaultValue={this.state[nameKey]}
        filterOption={(inputVal, opt) => {
          if (this.props.asyncSearch) return true;
          return this.handleFilter(inputVal, opt);
        }}
        onSelect={(val, comp) => {
          // console.log('sel', val, p2.props);
          this.isSelectAct = true;
          if (comp && comp.props) {
            this.changingVal = comp.props.text;
          }
          this.handleChange(val);
        }}
        onInputKeyDown={this.onInputKeyDown.bind(this)}
        dropdownMatchSelectWidth={false}
        dropdownStyle={{ width: 220 }}
        dropdownRender={this.dropdownRender.bind(this)}
        onPopupScroll={(e) => {
          if (30 >= e.target.scrollHeight - e.target.scrollTop - e.currentTarget.scrollHeight && this.props.totalPages > this.pageNo) {
            // 下一页
            console.log('>>>分页');
            this.pageNo++;
            this.fetchData(true);
          }
        }}
        {...nativeProps}
        style={opt.style || {}}
      >
        {map(compData, (opt, oK) => {
          const props = this.getOptionProps(opt, oK);
          return (
            opt ?
              <Option
                {...omit(props, ['children', 'value'])}
                value={`${opt[primaryKey]}`}
              >
                {
                  props.children
                }
              </Option>
              : null
          );
        })}
        <Option key={'empty'} value="" text={''} isempty={''} disabled={true}/>
      </AutoComplete>
    );
  }
}

AutoCompleteComp.defaultProps = {
  /* ObjectBox 组件的所以属性 */
  ...ObjectBox.defaultProps,
  asyncSearch: false, // Boolean 是否支持异步搜索，如果设置为 true，当输入值变化的时候，回实时调用 asyncReqFunc 进行请求
  asyncReqFunc: null, // Function 异步查询的执行方法
  initialPageNo: 1,
  totalPages: 0,
  quickAdd: true, // Boolean 是否可以快速添加，暂无用
};

export default connect(({ global }) => ({ global }))(AutoCompleteComp);
